package com.dream.myqiyi.db;

import java.sql.SQLException;  
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;  
import android.database.sqlite.SQLiteDatabase;  
import android.util.Log;  

import com.dream.myqiyi.Global;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.dao.NoteResourceModel;
import com.dream.myqiyi.dao.NoteTagsModel;
import com.dream.myqiyi.dao.NotebookModel;
import com.dream.myqiyi.dao.TagModel;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class MainDBHelper extends OrmLiteSqliteOpenHelper { 
	
	public static final String DATABASE_PATH = Global.dbDir + Global.databaseName + ".db";
	// the DAO object we use to access the SimpleData table
	
	private Dao<TagModel, String>					tagDao = null;
	private Dao<NotebookModel, String>				notebookDao = null;
	private Dao<NoteModel, String>					noteDao = null;
	private Dao<NoteTagsModel, Integer>				noteTagsDao = null;
	private Dao<NoteResourceModel, String>			noteResourceDao = null;

	private static final AtomicInteger usageCounter = new AtomicInteger(0);
	// we do this so there is only one helper
 	private static MainDBHelper helper = null;
	/**
	 * Get the helper, possibly constructing it if necessary. For each call to this method, there should be 1 and only 1
	 * call to {@link #close()}.
	 */
	public static synchronized MainDBHelper createSingleton(Context context) {
		if (helper == null) {
			helper = new MainDBHelper(context);
		}
		usageCounter.incrementAndGet();
		return helper;
	}
	
	public static synchronized MainDBHelper getSingleton() {
		usageCounter.incrementAndGet();
		return helper;
	}

    MainDBHelper(Context context) {  
        //CursorFactory设置为null,使用默认值  
        super(context, Global.databaseName, null, Global.databaseVersion);  
    }
    
    @Override
    public synchronized SQLiteDatabase getWritableDatabase() {
        return SQLiteDatabase.openDatabase(DATABASE_PATH, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    public synchronized SQLiteDatabase getReadableDatabase() {
        return SQLiteDatabase.openDatabase(DATABASE_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
    }

    //数据库第一次被创建时onCreate会被调用  
    @Override  
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {  
		try {
			Log.i(MainDBHelper.class.getName(), "onCreate");

			TableUtils.createTable(connectionSource, TagModel.class);
			TableUtils.createTable(connectionSource, NotebookModel.class);
			TableUtils.createTable(connectionSource, NoteModel.class);
			TableUtils.createTable(connectionSource, NoteTagsModel.class);
			TableUtils.createTable(connectionSource, NoteResourceModel.class);
			
			

			// here we try inserting data in the on-create as a test
			//Dao<DeletedItem, Integer> dao = getDeletedItemDao();
			long millis = System.currentTimeMillis();
			// create some entries in the onCreate
			//DeletedItem simple = new DeletedItem();
			//dao.create(simple);
			Log.i(MainDBHelper.class.getName(), "created new entries in onCreate: " + millis);
						
		} catch (SQLException e) {
			Log.e(MainDBHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
    }  
  
    //如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade  
    @Override  
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {  
		try {
			Log.i(MainDBHelper.class.getName(), "onUpgrade");
			
			
			TableUtils.dropTable(connectionSource, TagModel.class, true);
			TableUtils.dropTable(connectionSource, NotebookModel.class, true);
			TableUtils.dropTable(connectionSource, NoteModel.class, true);
			TableUtils.dropTable(connectionSource, NoteTagsModel.class, true);
			TableUtils.dropTable(connectionSource, NoteResourceModel.class, true);

			// after we drop the old databases, we create the new ones
			onCreate(db, connectionSource);
		} catch (SQLException e) {
			Log.e(MainDBHelper.class.getName(), "Can't drop databases", e);
			throw new RuntimeException(e);
		}
    }

	/**
	 * Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached
	 * value.
	 */
    public Dao<TagModel, String> getTagDao() {
    	if (tagDao == null) {
    		try {
				tagDao = getDao(TagModel.class);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	return tagDao;
    }
    public Dao<NotebookModel, String> getNotebookDao() {
    	if (notebookDao == null) {
    		try {
				notebookDao = getDao(NotebookModel.class);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				Log.e("[MyNeverNote]", e.getMessage());
				e.printStackTrace();
			}
    	}
    	return notebookDao;    		
    }
	public Dao<NoteModel, String> getNoteDao() {
		if (noteDao == null) {
			try {
				noteDao = getDao(NoteModel.class);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return noteDao;
	}
	public Dao<NoteTagsModel, Integer> getNoteTagsDao() {
		if (noteTagsDao == null) {
			try {
				noteTagsDao = getDao(NoteTagsModel.class);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return noteTagsDao;
	}
	public Dao<NoteResourceModel, String> getNoteResourceDao() {
		if (noteResourceDao == null) {
			try {
				noteResourceDao = getDao(NoteResourceModel.class);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return noteResourceDao;
	}

	/**
	 * Close the database connections and clear any cached DAOs. For each call to {@link #createSingleton(Context)}, there
	 * should be 1 and only 1 call to this method. If there were 3 calls to {@link #createSingleton(Context)} then on the 3rd
	 * call to this method, the helper and the underlying database connections will be closed.
	 */
	@Override
	public void close() {
		if (usageCounter.decrementAndGet() == 0) {
			super.close();
			
			tagDao = null;
			notebookDao = null;
			noteDao = null;
			noteTagsDao = null;
			noteResourceDao = null;
			
			helper = null;
		}
	}

}
